﻿/* ************************************************************************************* 
 * CREATED BY:          GIAPCM
 * CREATED DATE:        10/02/2009
 * PROJECT:             MC ENT WEBSITE PROJECT
 * PURPOSE:             
 * MODIFIED BY:         None
 * MODIFIED DATE:       None
 * MODIFIED REASON:     None
 * NOTES:               None
 **************************************************************************************/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MCWEBSITE.BUL;
using MCWEBSITE.ENTITY;
using System.Collections.Generic;
using System.IO;
using MCWF;

public partial class Modules_WebsiteBackEnd_wucNewsLetterDetail : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] ResourceDirectory = { "" };
        ResourceDirectory[0] = lblResourceDirectoryTemp.Text.Trim();
        this.SetEditorParameters(ResourceDirectory);
    }

    #region "UTILITIES"

    //SET PAPAMETERS FOR RAD EDITOR
    public void SetEditorParameters(string[] UploadDir)
    {
        //SET IMAGE MANAGER PATHS
        redtContentText.ImageManager.MaxUploadFileSize = 20971520; //20MB
        redtContentText.ImageManager.DeletePaths = UploadDir;
        redtContentText.ImageManager.ViewPaths = UploadDir;
        redtContentText.ImageManager.UploadPaths = UploadDir;

        //SET MEDIA MANAGER PATHS
        redtContentText.MediaManager.MaxUploadFileSize = 41943040; //40MB
        redtContentText.MediaManager.ViewPaths = UploadDir;
        redtContentText.MediaManager.UploadPaths = UploadDir;
        redtContentText.MediaManager.DeletePaths = UploadDir;

        //SET FLASH MANAGER PATHS
        redtContentText.FlashManager.MaxUploadFileSize = 41943040; //40MB
        redtContentText.FlashManager.ViewPaths = UploadDir;
        redtContentText.FlashManager.UploadPaths = UploadDir;
        redtContentText.FlashManager.DeletePaths = UploadDir;
    }
    #endregion

    #region "BINDING DATA CONTROLS"

    protected void BindDataDetail(int ItemID)
    {
        string[] ResourceDirectory = { "" };
        this.BindLanguage();
        if (ItemID != -1)
        {
            websiteNewsLetterInfo objNewsLetter = websiteNewsLetterBUL.Load(ItemID);
            lblNewsLetterID.Text = Convert.ToString(objNewsLetter.NewsLetterID);
            tbTitle.Text = objNewsLetter.Title;
            redtContentText.Content = objNewsLetter.Content.ToString();
            tbDescription.Text = objNewsLetter.Description;
            string Language = objNewsLetter.LanguageCode.ToString();
            this.rcbLanguage.Items.FindItemByValue(Language).Selected = true;
            // Check resource directory
            ResourceDirectory[0] = objNewsLetter.Atribute1;
            string ResourcePhysicalPath = Server.MapPath(ResourceDirectory[0]);
            DirectoryInfo ResourcePhysicalDir = new DirectoryInfo(ResourcePhysicalPath);
            if (!ResourcePhysicalDir.Exists)
            {
                ResourcePhysicalDir.Create();
            }
            lblResourceDirectoryTemp.Text = objNewsLetter.Atribute1;            
            // Assign parameter for RadUpload and RadEditor
            this.SetEditorParameters(ResourceDirectory);
        }
        else
        {
            lblNewsLetterID.Text = "";
            tbDescription.Text = "";
            redtContentText.Content = "";
            tbTitle.Text = "";
            // Resources directory
            ResourceDirectory[0] = "~/Resources/NewsLetter/temp";
            string TempDirectory = "";
            if (lblResourceDirectoryTemp.Text == "")
            {
                for (int i = 1; i <= 200; i++)
                {
                    TempDirectory = Server.MapPath(ResourceDirectory[0]);
                    TempDirectory = TempDirectory + "\\" + i.ToString() + "\\";
                    DirectoryInfo ResourcePhysicalDirectory = new DirectoryInfo(TempDirectory);
                    if (!ResourcePhysicalDirectory.Exists)
                    {
                        // Create resource directory
                        ResourcePhysicalDirectory.Create();
                        ResourceDirectory[0] = ResourceDirectory[0] + "\\" + ResourcePhysicalDirectory.Name;                        
                        lblResourceDirectoryTemp.Text = ResourceDirectory[0];                        
                        break;
                    }
                }
            }
            else
            {
                ResourceDirectory[0] = lblResourceDirectoryTemp.Text;
            }
            // Assign parameter for RadEditor
            this.SetEditorParameters(ResourceDirectory);
        }
    }

    protected void BindLanguage()
    {
        this.rcbLanguage.DataSource = websiteLanguageBUL.GetAll();
        this.rcbLanguage.DataTextField = "languageName";
        this.rcbLanguage.DataValueField = "LanguageCode";
        this.rcbLanguage.DataBind();
    }

    #endregion

    #region "DATA HANDLING PROCEDURE/FUNCTION"

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int InsertRow()
    {
        websiteNewsLetterInfo objNewsLetter = new websiteNewsLetterInfo();
        objNewsLetter.NewsLetterID = 0;
        objNewsLetter.Title = tbTitle.Text.Trim();
        objNewsLetter.Content = redtContentText.Content;
        objNewsLetter.Description = tbDescription.Text.Trim();
        objNewsLetter.LanguageCode = this.rcbLanguage.SelectedValue;
        objNewsLetter.Creater = HttpContext.Current.User.Identity.Name;
        try
        {
            // Save news object
            int InsertedNewsLetterId = websiteNewsLetterBUL.Save(objNewsLetter);
            // Moving all resource from temp directory to newly created one
            // Get CreateDate from database based on NewsId
            string CreateDate = websiteNewsLetterBUL.Load(InsertedNewsLetterId).CreateDate.ToString("yyyy-MM-dd").Replace("-", "_");
            string ResourceDirectory = "~/Resources/NewsLetter/" + CreateDate + "/" + InsertedNewsLetterId.ToString() + "/";            
            // Insert NewsThumbImg object to NewsThumbImg table
            websiteNewsLetterBUL.InsertResource(InsertedNewsLetterId, ResourceDirectory);
            // Processing resource 
            // Create resource directory and thumb directory approximately
            DirectoryInfo ResourcesDir = new DirectoryInfo(Server.MapPath(ResourceDirectory));
            if (!ResourcesDir.Exists) ResourcesDir.Create();            
            // Copy all resource from temp directory to newly created one
            Utilities.CopyDirectory(Server.MapPath(lblResourceDirectoryTemp.Text), Server.MapPath(ResourceDirectory), true);
            // Delete temp directory
            DirectoryInfo TempDir = new DirectoryInfo(Server.MapPath(lblResourceDirectoryTemp.Text));
            TempDir.Delete(true);
            // Update resource path in contenttext
            //objNews.NewsID = InsertedNewsId;
            //websiteNewsBUL.SaveComposeResource(objNews, HttpContext.Current.Request.ApplicationPath.Substring(1, Request.ApplicationPath.Length - 1));

            // Return result
            return 1;
        }
        catch
        {
            return -1;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int DeleteRow()
    {
        return websiteNewsLetterBUL.Remove(Convert.ToInt32(lblNewsLetterID.Text.Trim()));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int UpdateRow()
    {
        websiteNewsLetterInfo objNewsLetter = new websiteNewsLetterInfo();
        objNewsLetter.NewsLetterID = Convert.ToInt32(lblNewsLetterID.Text.Trim());
        objNewsLetter.Title = tbTitle.Text.Trim();
        objNewsLetter.Content = redtContentText.Content;
        objNewsLetter.Description = tbDescription.Text.Trim();
        objNewsLetter.LanguageCode = this.rcbLanguage.SelectedValue;
        objNewsLetter.Creater = HttpContext.Current.User.Identity.Name;
        return websiteNewsLetterBUL.Save(objNewsLetter);
    }

    #endregion

    #region "CONTROL EVENT HANDLER"


    #endregion

    #region "PUBLIC PROCEDURE/FUNCTION"
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ClickedButton"></param>
    /// <returns></returns>   
    public string PerformToolbarEvent(ToolbarButton ClickedButton)
    {
        string ResultString = "";
        int ReturnResult;

        if (lblCurrentMode.Text.ToString().ToUpper() == ToolbarStatus.NEW.ToString().ToUpper() &&
            ClickedButton == ToolbarButton.SAVEBUTTON)
        {
            if (Page.IsValid)
            {
                ReturnResult = this.InsertRow();
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được bổ xung thành công";
                else ResultString = "Lỗi trong quá trình bổ xung bản ghi";
            }
        }

        if (lblCurrentMode.Text.ToString().ToUpper() == ToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == ToolbarButton.SAVEBUTTON)
        {
            if (Page.IsValid)
            {
                ReturnResult = this.UpdateRow();
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được cập nhật thành công";
                else ResultString = "Lỗi trong quá trình cập nhật bản ghi";
            }
        }

        if (lblCurrentMode.Text.ToString().ToUpper() == ToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == ToolbarButton.DELBUTTON)
        {
            ReturnResult = this.DeleteRow();
            if ((int)ReturnResult > 0) ResultString = "Bản ghi được xóa thành công";
            else ResultString = "Lỗi trong quá trình xóa bản ghi";
        }

        return ResultString;
    }


    public void SetControlMode(ToolbarStatus ToolbarMode)
    {
        if (ToolbarMode == ToolbarStatus.NEW)
        {
            lblDetailMode.Text = "TẠO MỚI BẢN GHI";
            lblCurrentMode.Text = ToolbarStatus.NEW.ToString().ToUpper();
        }
        if (ToolbarMode == ToolbarStatus.EDIT)
        {
            lblDetailMode.Text = "CHỈNH SỬA BẢN GHI";
            lblCurrentMode.Text = ToolbarStatus.EDIT.ToString().ToUpper();
        }
    }

    public void SetDetailData(int ItemID)
    {
        this.BindDataDetail(ItemID);
    }

    public void RefreshDetailView()
    {
        if (lblCurrentMode.Text.ToString().ToUpper() == ToolbarStatus.NEW.ToString().ToUpper())
        {
            this.BindDataDetail(-1);
        }
        else
        {
            int SelectedItemID = Convert.ToInt32(lblNewsLetterID.Text.Trim());
            this.BindDataDetail(SelectedItemID);
        }
    }

    #endregion
}
